#!/bin/bash

project_root=$(pwd)
lib_path="$project_root/out/rk3568/lib.unstripped"
exe_path="$project_root/out/rk3568/exe.unstripped"
init=$1

function change_dir() {
  cd $1 &&
    echo "current directory:$(pwd)"
}

if [ $# -gt 0 ] && [ $init = init ]; then
  repo init -u git@gitee.com:openharmony/manifest.git -b master --no-repo-verify
fi
# sync
repo sync -c
repo forall -c 'git lfs pull'
bash build/prebuilts_download.sh
echo "prebuilts_download completed"

# build
./build.sh --product-name rk3568 --ccache &&
  echo "build with as-needed completed"
# gen good.log
change_dir $lib_path &&
  find . -name "*" -type f -printf "%p\n" | xargs -I param sh -c "echo param; readelf -d param | grep NEEDED" >$project_root/good.log
change_dir $exe_path &&
  find . -name "*" -type f -printf "%p\n" | xargs -I param sh -c "echo param; readelf -d param | grep NEEDED" >>$project_root/good.log
change_dir $project_root &&
  echo "good.log generated"
# comment as-needed
sed -in 's/\"-Wl,--as-needed\",/# \"-Wl,--as-needed\",/g' build/config/compiler/BUILD.gn &&
  echo "as-needed commented"

# build
./build.sh --product-name rk3568 --ccache &&
  echo "build without as-needed completed"
change_dir $lib_path &&
  find . -name "*" -type f -printf "%p\n" | xargs -I param sh -c "echo param; readelf -d param | grep NEEDED" >$project_root/bad.log
change_dir $exe_path &&
  find . -name "*" -type f -printf "%p\n" | xargs -I param sh -c "echo param; readelf -d param | grep NEEDED" >>$project_root/bad.log
change_dir $project_root &&
  echo "bad.log generated"

#uncomment as-needed
sed -in 's/# \"-Wl,--as-needed\",/\"-Wl,--as-needed\",/g' build/config/compiler/BUILD.gn &&
  echo "as-needed uncommented" &&
  echo "build completed" &&
  repo manifest >manifest.xml
pip3 install thefuzz &&
  python3 log_analysis.py
